// pages/product_detail/product_detail.ts

interface ProductFeature {
  icon: string;
  title: string;
  description: string;
}

interface ProductSpec {
  id: number;
  name: string;
  price: number;
  stock: number;
}

interface ProductPromotion {
  type: string;
  description: string;
}

interface ProductReview {
  id: number;
  username: string;
  avatar: string;
  rating: number;
  time: string;
  content: string;
  images: string[];
  spec: string;
}

interface Product {
  id: number;
  name: string;
  description: string;
  price: number;
  originalPrice: number;
  discount: number;
  sales: number;
  stock: number;
  positiveRate: string;
  rating: number;
  reviewCount: number;
  badges: string[];
  specs: ProductSpec[];
  promotions: ProductPromotion[];
  images: string[];
  features: ProductFeature[];
  params: Array<{name: string; value: string}>;
  detailContent: string;
  reviews: ProductReview[];
}

Page({
  data: {
    product: {
      id: 1,
      name: '贵州苗药足浴包（10袋装）',
      description: '采用贵州高山草药，纯天然配方，舒缓疲劳，促进血液循环',
      price: 128.00,
      originalPrice: 168.00,
      discount: 7.6,
      sales: 589,
      stock: 999,
      positiveRate: '98%',
      rating: 4.9,
      reviewCount: 352,
      badges: ['清热解毒', '舒缓疲劳', '传统苗药'],
      specs: [
        { id: 1, name: '10袋装', price: 128.00, stock: 999 },
        { id: 2, name: '20袋装', price: 228.00, stock: 568 },
        { id: 3, name: '礼盒装', price: 288.00, stock: 326 }
      ],
      promotions: [
        { type: '满减', description: '满200减20，满300减50' },
        { type: '特惠', description: '新人首单立减10元' }
      ],
      images: [
        'https://images.unsplash.com/photo-1591189863430-ab87e7f8e8dd',
        'https://images.unsplash.com/photo-1556760544-74068565f05c',
        'https://images.unsplash.com/photo-1586325194227-7625ed95172b'
      ],
      features: [
        {
          icon: 'heart',
          title: '纯天然草药',
          description: '精选贵州高山野生药材，不含任何化学添加剂，安全无刺激'
        },
        {
          icon: 'root-list',
          title: '传统苗医配方',
          description: '传承百年苗医配方，选用20余种天然药材，科学配比'
        },
        {
          icon: 'bulletpoint',
          title: '多重康养功效',
          description: '舒缓疲劳、促进血液循环、改善睡眠质量、缓解肌肉酸痛'
        },
        {
          icon: 'discount',
          title: '便捷使用',
          description: '独立小包装，一次一袋，冲泡简单，无需熬制'
        }
      ],
      params: [
        { name: '品名', value: '贵州苗药足浴包' },
        { name: '配料', value: '苗药材（苦参、艾叶、川椒、花椒、柏叶等）' },
        { name: '净含量', value: '10袋/盒，每袋25g' },
        { name: '生产日期', value: '见包装' },
        { name: '保质期', value: '24个月' },
        { name: '储存方法', value: '置于阴凉干燥处' },
        { name: '使用方法', value: '将足浴包放入足浴盆中，加入40℃左右温水浸泡5分钟后使用' },
        { name: '适用人群', value: '成人（孕妇、婴幼儿慎用）' },
        { name: '生产厂家', value: '贵州康养药业有限公司' },
        { name: '厂址', value: '贵州省贵阳市观山湖区高新技术产业开发区' }
      ],
      detailContent: `
        <div style="font-size:28rpx;line-height:1.8;color:#333;">
          <h3 style="font-size:32rpx;font-weight:bold;margin:20rpx 0;color:#333;">产品简介</h3>
          <p>贵州苗药足浴包采用贵州高山野生药材，传承苗族古法配方，精选20余种名贵草药，经过科学配比，研制而成。</p>
          <p>足浴是中医养生保健的重要方式之一，通过药浴，可刺激足部穴位，促进血液循环，调节身体机能，达到舒缓疲劳、改善睡眠的功效。</p>
          <img src="https://images.unsplash.com/photo-1636395374451-2a58453fcee7" style="width:100%;margin:20rpx 0;border-radius:8rpx;" />
          
          <h3 style="font-size:32rpx;font-weight:bold;margin:20rpx 0;color:#333;">主要成分</h3>
          <p>苦参：清热解毒，燥湿杀虫</p>
          <p>艾叶：温经止血，散寒止痛</p>
          <p>川椒：温中散寒，除湿解表</p>
          <p>花椒：温中散寒，杀虫止痒</p>
          <p>柏叶：除湿止痒，杀虫消毒</p>
          <p>等20余种珍贵中草药</p>
          
          <h3 style="font-size:32rpx;font-weight:bold;margin:20rpx 0;color:#333;">使用方法</h3>
          <p>1. 将足浴包放入足浴盆中</p>
          <p>2. 加入40℃左右温水，浸泡5分钟，使药效充分释放</p>
          <p>3. 泡脚时间建议20-30分钟</p>
          <p>4. 泡脚结束后，用清水冲洗双脚</p>
          <img src="https://images.unsplash.com/photo-1595161397851-cb000fbce74e" style="width:100%;margin:20rpx 0;border-radius:8rpx;" />
          
          <h3 style="font-size:32rpx;font-weight:bold;margin:20rpx 0;color:#333;">注意事项</h3>
          <p>1. 请置于阴凉干燥处，避免阳光直射</p>
          <p>2. 孕妇、婴幼儿以及对草药过敏者慎用</p>
          <p>3. 泡脚水温不宜过高，以免烫伤</p>
          <p>4. 如有不适，请立即停止使用</p>
        </div>
      `,
      reviews: [
        {
          id: 1,
          username: '晴天',
          avatar: 'https://images.unsplash.com/photo-1438761681033-6461ffad8d80',
          rating: 5,
          time: '2023-10-15',
          content: '真的很好用！每天下班回来泡20分钟，疲劳感一扫而空，睡眠质量也提高了。药材味道很纯正，不刺激，泡完脚后皮肤很舒服。包装也很好看，准备再买几盒送给家人。',
          images: [
            'https://images.unsplash.com/photo-1611074863839-5d482d49c39e',
            'https://images.unsplash.com/photo-1606767041004-0bb2b59467b6'
          ],
          spec: '10袋装'
        },
        {
          id: 2,
          username: '草木者',
          avatar: 'https://images.unsplash.com/photo-1570295999919-56ceb5ecca61',
          rating: 5,
          time: '2023-09-30',
          content: '这个足浴包挺不错的，能明显感觉到药效。我爸妈年纪大了，常年腿脚不适，用了一段时间说有明显改善。苗药配方确实有其独到之处，推荐给有需要的朋友。',
          images: [],
          spec: '20袋装'
        },
        {
          id: 3,
          username: '小鱼儿',
          avatar: 'https://images.unsplash.com/photo-1546961329-78bef0414d7c',
          rating: 4,
          time: '2023-09-25',
          content: '泡完脚确实很舒服，腿部感觉轻松了不少。唯一不足的是药包有点小，建议可以做大一点，药效会更足。总体来说还是不错的产品，会回购。',
          images: [
            'https://images.unsplash.com/photo-1586325194227-7625ed95172b'
          ],
          spec: '礼盒装'
        }
      ]
    } as Product,
    selectedSpec: 0, // 选中的规格索引
    quantity: 1, // 选择的数量
    tabValue: 'detail', // 当前选中的标签页
    scrolled: false, // 是否已滚动
    isFavorite: false, // 是否收藏
    cartCount: 8, // 购物车商品数量
    reviewFilter: 'all', // 评价筛选
    filteredReviews: [] as ProductReview[], // 筛选后的评价
    showSpecsPopup: false // 规格选择弹窗是否显示
  },

  onLoad: function (options: Record<string, string>) {
    // 获取商品ID
    const id = options.id;
    if (id) {
      // 根据ID从服务器获取商品详情
      // this.getProductDetail(id);
    }
    
    // 初始化筛选后的评价列表
    this.setData({
      filteredReviews: this.data.product.reviews
    });
  },

  onReady: function () {
    // 监听页面滚动
    wx.createIntersectionObserver().relativeToViewport().observe('.gallery-container', (res) => {
      if (res.intersectionRatio < 0.5) {
        this.setData({ scrolled: true });
      } else {
        this.setData({ scrolled: false });
      }
    });
  },

  // Tab切换
  onTabChange: function (e: any) {
    this.setData({
      tabValue: e.detail.value
    });
  },

  // 返回上一页
  navigateBack: function () {
    wx.navigateBack();
  },

  // 分享
  handleShare: function () {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  // 收藏
  handleFavorite: function () {
    this.setData({
      isFavorite: !this.data.isFavorite
    });
    
    wx.showToast({
      title: this.data.isFavorite ? '已收藏' : '已取消收藏',
      icon: 'success'
    });
  },

  // 预览图片
  previewImage: function (e: any) {
    const index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.product.images[index],
      urls: this.data.product.images
    });
  },

  // 预览评价图片
  previewReviewImage: function (e: any) {
    const reviewIndex = e.currentTarget.dataset.reviewIndex;
    const imgIndex = e.currentTarget.dataset.imgIndex;
    const review = this.data.product.reviews[reviewIndex];
    
    wx.previewImage({
      current: review.images[imgIndex],
      urls: review.images
    });
  },

  // 选择规格
  selectSpec: function (e: any) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      selectedSpec: index
    });
  },

  // 查看所有规格
  viewAllSpecs: function () {
    this.setData({
      showSpecsPopup: true
    });
  },

  // 隐藏规格选择弹窗
  hideSpecsPopup: function () {
    this.setData({
      showSpecsPopup: false
    });
  },

  // 确认规格选择
  confirmSelection: function () {
    this.hideSpecsPopup();
    
    // 这里可以处理选择完成后的逻辑
    // 例如更新价格、库存等
  },

  // 数量变化
  onQuantityChange: function (e: any) {
    this.setData({
      quantity: e.detail.value
    });
  },

  // 查看全部评价
  viewAllReviews: function () {
    this.setData({
      tabValue: 'reviews'
    });
  },

  // 筛选评价
  setReviewFilter: function (e: any) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({
      reviewFilter: filter
    });
    this.filterReviews();
  },

  // 处理评价筛选
  filterReviews: function () {
    let reviews = this.data.product.reviews;
    let filtered: ProductReview[] = [];
    
    switch (this.data.reviewFilter) {
      case 'positive':
        filtered = reviews.filter(review => review.rating >= 4);
        break;
      case 'latest':
        filtered = [...reviews].sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime());
        break;
      default:
        filtered = reviews;
    }
    
    this.setData({
      filteredReviews: filtered
    });
  },

  // 查看更多评价
  viewMoreReviews: function () {
    // 这里可以加载更多评价
    wx.showToast({
      title: '加载更多评价',
      icon: 'none'
    });
  },

  // 导航到首页
  navigateToHome: function () {
    wx.switchTab({
      url: '/pages/home/home'
    });
  },

  // 导航到购物车
  navigateToCart: function () {
    wx.navigateTo({
      url: '/pages/cart/cart'
    });
  },

  // 联系客服
  contactService: function () {
    wx.showToast({
      title: '正在连接客服...',
      icon: 'none'
    });
  },

  // 加入购物车
  addToCart: function () {
    const spec = this.data.product.specs[this.data.selectedSpec];
    
    wx.showToast({
      title: '已加入购物车',
      icon: 'success'
    });
    
    // 更新购物车数量
    this.setData({
      cartCount: this.data.cartCount + this.data.quantity
    });
    
    // 这里应该调用API将商品添加到购物车
  },

  // 立即购买
  buyNow: function () {
    const spec = this.data.product.specs[this.data.selectedSpec];
    
    wx.navigateTo({
      url: `/pages/order_detail/order_detail?id=${this.data.product.id}&spec_id=${spec.id}&quantity=${this.data.quantity}&type=product`
    });
  },

  // 获取商品详情
  getProductDetail: function (id: string) {
    wx.showLoading({
      title: '加载中',
    });
    
    // 这里应该是从服务器获取数据
    // 模拟API请求
    setTimeout(() => {
      // 如果是真实环境，这里会用实际接口返回的数据更新this.data.product
      
      // 获取完数据后，初始化筛选后的评价列表
      this.setData({
        filteredReviews: this.data.product.reviews
      });
      
      wx.hideLoading();
    }, 500);
  },

  onShareAppMessage: function () {
    return {
      title: `【贵州四季康养】${this.data.product.name}`,
      path: `/pages/product_detail/product_detail?id=${this.data.product.id}`,
      imageUrl: this.data.product.images[0]
    };
  }
}) 